<template>
  <a-modal
    class="commodity-form"
    :visible="formVisible"
    :title="title"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    :closable="false"
    :confirmLoading="confirmLoading"
    width="1000px"
    @cancel="closeModal(false)"
    @ok="handleSubmit">
    <search-table
      :url="listUrl"
      ref="searchtable"
      :columns="columns"
      :defaultParams="defaultParams"
      :headParams="headParams"
      :form="form"
      :beforeRenderFunc="beforeRenderFunc"
      @selectedRowChange="selectGoods">
      <template slot="searchForm">
        <a-form layout="inline" :form="form">
          <a-form-item label="商品名称">
            <a-input
              style="width:180px"
              v-decorator="[
                'name',
              ]"
              placeholder="请输入商品名称">
            </a-input>
          </a-form-item>
          <a-form-item label="商品分类">
            <a-tree-select
              allowClear
              style="width:180px"
              :replaceFields="{children:'children', title:'classifyName', key:'id', value: 'id' }"
              v-decorator="[
                'goodsClassificationId',
              ]"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="productClassifyList"
              placeholder="请选择"
              tree-default-expand-all
              >
              <span slot="title" slot-scope="{ value }">
                  {{ value }}
              </span>
            </a-tree-select>
          </a-form-item>
          <a-form-item label="商品类目">
              <a-tree-select
                allowClear
                style="width:180px"
                :replaceFields="{children:'children', title:'categoryName', key:'id', value: 'id' }"
                v-decorator="[
                  'goodsCategoryId',
                ]"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="productCategoryList"
                placeholder="请选择"
                tree-default-expand-all
                >
                <span slot="title" slot-scope="{ value }">
                    {{ value }}
                </span>
            </a-tree-select>
          </a-form-item>
          <a-form-item label="商品分组">
            <a-tree-select
                allowClear
                style="width:180px"
                :replaceFields="{children:'children', title:'groupName', key:'id', value: 'id' }"
                v-decorator="[
                  'goodsGroupId',
                ]"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="productGroupList"
                placeholder="请选择"
                tree-default-expand-all
                >
                <span slot="title" slot-scope="{ value }">
                    {{ value }}
                </span>
            </a-tree-select>
          </a-form-item>
          <a-form-item v-show="userInfo.shopRoleCode == 'role:store:main'" label="商品所属">
            <a-select style="width: 180px"
              v-decorator="[
                'goodsAscription',
              ]" :allowClear="true" placeholder="全部" :options="goodsAscriptionList"></a-select>
          </a-form-item>
        </a-form>
      </template>
    </search-table>
    <template slot="footer">
      <span style="margin-right: 20px">已选择 {{ total || 0 }} 款商品</span>
      <a-button :loading="confirmLoading" key="submit" type="primary" @click="handleSubmit"> 添加并上架 </a-button>
      <a-button key="back" @click="closeModal(false)"> 关闭 </a-button>
    </template>
  </a-modal>
</template>

<script>
  import { findDictNameByValue,createOptionsByDict } from '@/utils/dict'
  const appId = createOptionsByDict('LIVE_APPID')[0] ? createOptionsByDict('LIVE_APPID')[0].value : '100000054' // 直播平台id
  export default {
    name: "commodityForm",
    props: {
      roomId: {
        type: String,
        default: ''
      },
      appId: {
        type: String,
        default: ''
      },
      hasChosenGoodsIds: { // 已被选择的商品id集合
        type: Array,
        default:() => []
      },
    },
    data() {
      return {
        formVisible: false, // 是否显示选择商品弹窗
        title: '追加商品', // 弹窗标题
        listUrl: '/product/page', // 列表接口地址
        form: this.$form.createForm(this, { name: "table_search" }), // 搜索条件表格
        headParams: { baseURL: '/goldenhome/gh/live/admin' }, // 列表接口域名
        defaultParams: { // 列表默认携带参数
          appId: this.appId,
          productStatus: 1,
          auditStatus: 2
        },
        confirmLoading: false, // 弹窗提交状态
        productClassifyList:[], // 商品分类
        productCategoryList:[], // 商品类目
        productGroupList:[], // 商品分组
        goodsAscriptionList:[ // 商品所属
          {
            label:'本店商品',
            value:1
          },{
            label:'总店商品',
            value:2
          }
        ],
        goodsStatusList:[ // 商品状态
          {
            label:'仓库中',
            value:1
          },{
            label:'上架',
            value:2
          },{
            label:'已下架',
            value:3
          },
        ],
        columns: [
          {
            title: "商品ID",
            dataIndex: "goodsId",
            width: 125,
            key: "goodsId",
          },
          {
            title: "商品名称",
            dataIndex: "name",
            width: 320,
            key: "name"
          },
          {
            title: "添加方式",
            dataIndex: "thirdPartyTag",
            width: 125,
            key: "thirdPartyTag",
            customRender: (text, record) => findDictNameByValue('LIVE_GOOD_SOURCE', text)
          },
          {
            title: "价格",
            dataIndex: "price",
            key: "price",
            customRender: (text, record) => {
              let res = ''
              if(record.priceType == 1){
                res = (Number(record.price)/100).toFixed(2)+'元'
              } else if(record.priceType == 2) {
                res = (Number(record.price)/100).toFixed(2)+'元-'+(Number(record.price2)/100).toFixed(2)+'元'
              } else if(record.priceType == 3) {
                res = <span>市场价 {(Number(record.price)/100).toFixed(2)}元<br/>现价 {(Number(record.price2)/100).toFixed(2)}元</span>
              }
              return res
            }
          },
          {
            title: "总可售库存",
            dataIndex: "goodsInventoryTotal",
            key: "goodsInventoryTotal",
            customRender: (text, record) => {
              return text ? (text + (record.goodsUnitCode ? findDictNameByValue('GOOD_INVENTORY_UNIT', record.goodsUnitCode) : '')) : ''
            }
          },
        ],
        total: 0
      }
    },
    computed:{
      // 用户信息
      userInfo(){
        return this.$store.getters.userInfo || {};
      }
    },
    // watch: {
    //   formVisible(newVal){
    //     if(newVal){
    //       console.log(this.hasChosenGoodsIds)
    //     }
    //   }
    // },
    created(){
      this.getProductClassify(); // 分类
      this.getProductGroup(); // 分组
      this.getProductCategory(); // 类目
    },
    methods: {
      // 处理表格数据
      beforeRenderFunc(data) {
        let _this = this
        data.dataInfo.records.forEach(item => {
          if(_this.hasChosenGoodsIds.includes(item.id)) {
            item.disabled = true
          }
        })
        return data
      },
      // 商品状态
      getStatusLabelByStatusValue(value){
        return this.goodsStatusList.find(item=>{
          return item.value==value;
        })
      },
      // 商品分类
      async getProductClassify(){
        let res=await this.$get('/goods/classify/tree',{
          shopId:this.userInfo.shopId || ''
        });
        if(res && res.returnCode=='1000'){
          this.productClassifyList=res.dataInfo || [];
        }
        else {
          this.productClassifyList=[];
        }
      },
      // 商品类目
      async getProductCategory(){
        let res=await this.$get('/goods/category/tree',{
          categoryStatus:1
        },false,true);
        if(res && res.returnCode=='1000'){
          this.productCategoryList=res.dataInfo || [];
        }
        else {
          this.productCategoryList=[];
        }
      },
      // 商品分组
      async getProductGroup(){
        let res=await this.$get('/goods/group/tree',{
          shopId:this.userInfo.shopId || ''
        },false,true);
        if(res && res.returnCode=='1000'){
          this.productGroupList=res.dataInfo || [];
        }
        else {
          this.productGroupList=[];
        }
      },
      // 确定提交
      handleSubmit() {
        this.confirmLoading = true;
        if(this.$refs.searchtable.selectedRows.length > 0) {
          let goodsIds = this.$refs.searchtable.selectedRows.map((item) => {
            return item.goodsId
          })
          let params = {}
          params.goodsIds = goodsIds
          params.roomId = this.roomId
          params.appId = this.appId
          this.$post('/product/goodsShelves',
            params,
            { baseURL: `${location.origin}/goldenhome/gh/live/admin` })
          .then(res => {
            if(res && res.returnCode=='1000'){
              this.confirmLoading = false
              this.closeModal(true)
              this.$message.success('追加成功');
            } else {
              this.confirmLoading = false
              this.$message.error('追加失败');
            }
          })
          .catch(err => {
            this.confirmLoading = false
          })
        } else {
          this.$confirm({
            title: '关闭确认',
            content: '还未追加商品，确认要关闭此窗口吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
              this.confirmLoading = false
              this.closeModal(false)
            }
          });
        }
      },
      // 取消
      closeModal(bool) {
        console.log(bool)
        this.formVisible = false;
        this.$emit('cancel', bool)
      },
      // 勾选商品
      selectGoods(rows) {
        this.total = rows.length;
      }
    }
  }
</script>

<style scoped>

</style>
